package com.lixin.juc.semaphore;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class MainApplication {
    public static void main(String[] args) {
        // 最多有2个线程在运行，其他线程需要等待正在运行的2个线程中某一个线程运行完毕，才可运行
        Semaphore semaphore = new Semaphore(2);
        for (int i = 1; i <= 4; i++) {
            int finalI = i;
            new Thread(() -> {
                try {
                    semaphore.acquire();
                    System.out.println("线程" + finalI + "开始运行");
                    TimeUnit.SECONDS.sleep(3);
                    semaphore.release();
                    System.out.println("线程" + finalI + "运行完毕");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }, String.valueOf(i)).start();
        }
    }
}
